import model.MonthProductCondition
import util.DateUtils
import util.SellIdGenerator
import java.text.SimpleDateFormat

class ExportProductController {

    def  mailService
    def idGenerator = new SellIdGenerator()
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        if(!params.offset) params.offset = 0
        if(!params.sort) params.sort = "id"
        if(!params.order) params.order = "desc"
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ exportProductInstanceList: ExportProduct.list( params ), exportProductInstanceTotal: ExportProduct.count() ]
    }

   def listSearch = {
        // 搜索日期不为空的情况
        if (params.searchDate_value ){
            def year = params.searchDate_year
            def month = params.searchDate_month
            def day = params.searchDate_day
            def searchDateStr = year + "-" + month + "-" + day
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
            Date searchDate = sdf.parse(searchDateStr)

            def criteria = ExportProduct.createCriteria()
            def resultList = criteria.list(params){
                ge("time",searchDate)
                le("time",searchDate+1)
            }
            render(view:"listSearch" , model:[exportProductInstanceList:resultList])
        }
        // 搜索日期为空的情况
        else
            redirect(action:'list')
    }
    
    def show = {
        def exportProductInstance = ExportProduct.get( params.id )

        if(!exportProductInstance) {
            flash.message = "ExportProduct not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ exportProductInstance : exportProductInstance ] }
    }

    def delete = {
        def exportProductInstance = ExportProduct.get( params.id )

        def amount = exportProductInstance.amount
        def outPrice = exportProductInstance.outPrice
        def inPrice = exportProductInstance.inPrice
        def sellProductId = exportProductInstance.id
        def pureProfits = (outPrice - inPrice)*amount
        def profit = Profit.findByPureProfitsAndSellProductId(pureProfits,sellProductId)
        profit.delete()//删除利润
        
        if(exportProductInstance) {
            try {
                exportProductInstance.delete()
                flash.message = "ExportProduct ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "ExportProduct ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "ExportProduct not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def exportProductInstance = ExportProduct.get( params.id )

        if(!exportProductInstance) {
            flash.message = "ExportProduct not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ exportProductInstance : exportProductInstance ]
        }
    }

    def update = {
        def number = params.number
        def amount = params.amount
        def importProduct = ImportProduct.findByNumber(number)

        def importProductAmount = importProduct.getAmount()
        def hql = "select sum(p.amount) from ExportProduct p where p.number='"+number+"'"
        def result = ExportProduct.executeQuery(hql)
        def remain = importProductAmount - result[0]
        if (amount.toLong() > remain)
        {
            flash.message = "对不起，该批货物数量不够，请重新输入!!"
            redirect(action:"edit", params:[productName:params.productName,inPrice:params.inPrice,outPrice:params.outPrice,modelNo:params.modelNo,number:params.number,id:params.id])
            return
        }
        
        def exportProductInstance = ExportProduct.get( params.id )
        if(exportProductInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(exportProductInstance.version > version) {
                    exportProductInstance.errors.rejectValue("version", "exportProduct.optimistic.locking.failure", "Another user has updated this ExportProduct while you were editing.")
                    render(view:'edit',model:[exportProductInstance:exportProductInstance])
                    return
                }
            }
            exportProductInstance.properties = params
            if(!exportProductInstance.hasErrors() && exportProductInstance.save()) {
                def profit = Profit.findBySellProductId(params.id)
                def pureProfits = (exportProductInstance.outPrice-exportProductInstance.inPrice)*exportProductInstance.amount
                profit.setPureProfits(pureProfits)
                profit.save()
                flash.message = "ExportProduct ${params.id} updated"
                redirect(action:show,id:exportProductInstance.id)
            }
            else {
                render(view:'edit',model:[exportProductInstance:exportProductInstance])
            }
        }
        else {
            flash.message = "ExportProduct not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def exportProductInstance = new ExportProduct()
        exportProductInstance.properties = params
        return ['exportProductInstance':exportProductInstance]
    }

    def save = {
        def number = params.number
        def amount = params.amount
        def importProduct = ImportProduct.findByNumber(number)

        def importProductAmount = importProduct.getAmount()
        def hql = "select sum(p.amount) from ExportProduct p where p.number='"+number+"'"
        def result = ExportProduct.executeQuery(hql)
        def resultAmount
        if (result == [null])
        {
            resultAmount = 0
        }
        else
        {
            resultAmount = result[0]
        }
        println resultAmount
        def remain = importProductAmount - resultAmount
        if (amount.toLong() > remain)
        {
            flash.message = "对不起，该批货物数量不够，请重新输入!!"
            redirect(action:"create", params:[productName:params.productName,inPrice:params.inPrice,outPrice:params.outPrice,modelNo:params.modelNo,number:params.number])
            return
        }
        def sellNumber = "销售号"+idGenerator.getId()
        def exportProductInstance = new ExportProduct(params)
        if(!exportProductInstance.hasErrors() && exportProductInstance.save()) {

            exportProductInstance.setSellNumber(sellNumber)
            
            def pureProfits = (exportProductInstance.outPrice-exportProductInstance.inPrice)*exportProductInstance.amount
            Profit profit = new Profit()
            profit.setPureProfits(pureProfits)
            def date = new Date()
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
            def dateStr = sdf.format(date)
            def date2 = sdf.parse(dateStr)
            profit.setSellTime(date2)
            profit.setSellProductId(exportProductInstance.id)
            profit.save()
            
            flash.message = "ExportProduct ${exportProductInstance.id} created"
            redirect(action:show,id:exportProductInstance.id)
        }
        else {
            render(view:'create',model:[exportProductInstance:exportProductInstance])
        }
    }

    //产品售出
    def sellDetail ={
        def productInstance = new ExportProduct()
        productInstance.properties = params
        def supplier = Supplier.findBySupplierName(params.supplierName)
        def supplierId = supplier.getId()
        def catalog = Catalog.findByCatalogName(params.catalogName)
        def catalogId = catalog.getId()
        productInstance.number = params.id
        return ['productInstance':productInstance,supplierId:supplierId,catalogId:catalogId]
    }

    // 保存售出产品信息
    def sellSave = {
        def sellNumber = "销售号"+idGenerator.getId()
        def remain = params?.remain
        def productInstance = new ExportProduct(params)
        if(!productInstance.hasErrors() && productInstance.save()) {
            productInstance.setSellNumber(sellNumber)
            if (remain == params.amount)
            {
                def number = productInstance.getNumber()
                def resultList = ExportProduct.findAllByNumber(number)
                resultList.each{
                    it.hasSellOut="true"
                }
                mailService.sendMail {
                    to "fengzhizi715@126.com"
                    subject "沈哲，您好, "+number+" 该批次货物已售完"
                    body "沈哲，您好,进货号："+number+"该批次货物已售完"
                }
            }
            
            def pureProfits = (productInstance.outPrice-productInstance.inPrice)*productInstance.amount
            Profit profit = new Profit()
            profit.setPureProfits(pureProfits)
            def date = new Date()
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
            def dateStr = sdf.format(date)
            def date2 = sdf.parse(dateStr)
            profit.setSellTime(date2)
            profit.setSellProductId(productInstance.id)
            profit.save()
            
            flash.message = "Product ${productInstance.id} created"
            redirect(action:show,id:productInstance.id)
        }
        else {
            render(view:'create',model:[productInstance:productInstance])
        }
    }

    // 每月销售排行榜
    def monthProductCharts ={
    }

    def doMonthProductCharts = {
        def year = params.pickDate_year
        def month = params.pickDate_month
        def iYear = Integer.parseInt(year)
        def iMonth = Integer.parseInt(month)

        def startDate = DateUtils.getMonthStart(year,month)
        def iDay = DateUtils.getMonthOfDays(iYear,iMonth)

        def c = Calendar.getInstance()
        c.set(iYear,iMonth-1,iDay)
        def endDate = c.getTime()

        def hql = "select p.modelNo,sum(p.amount) from ExportProduct p where p.time >= ? and p.time <= ? group by p.modelNo"
        def resultList = ExportProduct.executeQuery(hql,[startDate,endDate])
        if (resultList.size()==0)
        {
            render(view:"productChartsError");
        }
        else{
            def dataList = []
            resultList.each { s->
                def bar = ['modelNo':s[0], 'amount':s[1]]
                dataList << bar
            }
            render(view:"monthProductCharts",model:[productChartList: dataList])
        }
    }

     // 销售排行榜
    def productCharts ={
        def hql = "select p.modelNo,sum(p.amount) from ExportProduct p group by p.modelNo"
        def resultList = ExportProduct.executeQuery(hql)
        if (resultList.size()==0)
        {
            render(view:"productChartsError");
        }
        else{
            def dataList = []
            resultList.each { s->
                def bar = ['modelNo':s[0], 'amount':s[1]]
                dataList << bar
            }
            [productChartList: dataList]
        }
    }

    // 按照月查询报表
    def everyMonthProductReport = {
    }

    def doEveryMonthProductReport = {
        def year = params.pickDate_year
        def month = params.pickDate_month
        def iYear = Integer.parseInt(year)
        def iMonth = Integer.parseInt(month)

        def startDate = DateUtils.getMonthStart(year,month)
        def iDay = DateUtils.getMonthOfDays(iYear,iMonth)

        def c = Calendar.getInstance()
        c.set(iYear,iMonth-1,iDay)
        def endDate = c.getTime()
        
        def criteria = ExportProduct.createCriteria()
        def resultList = criteria.list(){
            ge("time",startDate)
            le("time",endDate)
        }

        render(view:"everyMonthProductReport" , model:[productInstanceList: resultList,startDate:startDate,endDate:endDate])
    }

     // 将每月的报表查询结果导出成excel的Action
    def everyMonthProductReportExport = {
        response.setHeader("Content-disposition", "attachment; filename=requests.xls")
        response.contentType = "application/vnd.ms-excel"

        //定义header map
        def header = [:]

        header.productName = "产品名称"
        header.amount = "数量"
        header.inPrice = "进价"
        header.modelNo = "型号"
        header.outPrice = "零售价"
        header.supplier = "零售商"
        header.catalog = "产品分类"
        header.time = "进货时间"
        header.productFlag = "货品情况"

        def startDate=params.startDate
        SimpleDateFormat sdf= new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US)
        Date d1 = sdf.parse(startDate)

        def endDate = params.endDate
        Date d2 = sdf.parse(endDate)

        def criteria = ExportProduct.createCriteria()
        def resultList = criteria.list{
            ge("time",d1)
            le("time",d2)
        }
        ExcelUtils.writeExcel(response.outputStream, header, resultList)
    }

    // 月报表查询的Action
    def monthProductReport = { MonthProductCondition  monthProductCondition ->
        if(request.method == "POST") {
            if(!params.sort) params.sort = "id"
            if(!params.order) params.order = "desc"

            def startDate = monthProductCondition.startDate
            def endDate = monthProductCondition.endDate

    		def criteria = ExportProduct.createCriteria()

    		def resultList = criteria.list(params){
                ge("time",startDate)
                le("time",endDate)
    		}
    		render(view:"monthProductReportList" , model:[productList: resultList,startDate:startDate,endDate:endDate]);
    	}
    }

    // 将月报表查询结果导出成excel的Action
    def monthProductReportExport = {
        response.setHeader("Content-disposition", "attachment; filename=requests.xls")
        response.contentType = "application/vnd.ms-excel"

        //定义header map
        def header = [:]

        header.productName = "产品名称"
        header.amount = "数量"
        header.inPrice = "进价"
        header.modelNo = "型号"
        header.outPrice = "零售价"
        header.supplier = "零售商"
        header.catalog = "产品分类"
        header.time = "进货时间"
        header.productFlag = "货品情况"

        def startDate=params.startDate
        SimpleDateFormat sdf= new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US)
        Date d1 = sdf.parse(startDate)

        def endDate = params.endDate
        Date d2 = sdf.parse(endDate)

        def criteria = ExportProduct.createCriteria()
        def resultList = criteria.list{
            ge("time",d1)
            le("time",d2)
        }
        ExcelUtils.writeExcel(response.outputStream, header, resultList)
    }

}
